import time
from selenium import webdriver
from PIL import Image,ImageEnhance
import pytesseract


def get_auth_code(driver,codeEelement):
    driver.save_screenshot('login/login.png')
    imgSize = codeEelement.size
    imgLocation = imgElement.location
    rangle = (int(imgLocation['x']),int(imgLocation['y']),int(imgLocation['x'] + imgSize['width']),int(imgLocation['y']+imgSize['height']))
    login = Image.open("login/login.png")  
    frame4=login.crop(rangle) 
    frame4.save('login/authcode.png')
    authcodeImg = Image.open('login/authcode.png')
    authCodeText = pytesseract.image_to_string(authcodeImg).strip()
    return authCodeText

def pandarola_login(driver,account,passwd,authCode):
    driver.find_element_by_name('username').send_keys(account) #"/html/body/div[2]/ul/li/form/div/ul/div[1]/input"
    driver.find_element_by_name('passwd').send_keys(passwd) #"/html/body/div[2]/ul/li/form/div/ul/div[2]/input"
    driver.find_element_by_name('piccode').send_keys(authCode) #"/html/body/div[2]/ul/li/form/div/ul/div[3]/input"
    driver.find_element_by_xpath('/html/body/div[2]/ul/li/form/div/ul/div[4]/button').click() 
    time.sleep(3)
    title = driver.find_element_by_id('/html/body/div[1]/div[2]/div[1]/div[4]/a').text 
    try:
        assert title == '' 
        return 'PASS'
    except AssertionError as e:
        return 'FAIL'

if False:
    driver.get('https://44dby.com')
    driver.maximize_window()
    imgElement = driver.find_element_by_xpath('/html/body/div[2]/ul/li/form/div/ul/div[3]/img')
    authCodeText = get_auth_code(driver,imgElement)
    
    while True:
        psp = pandarola_login(driver,'bhlt17','baidu123456',authCodeText)
        if psp == 'PASS':
            break
        else:
            time.sleep(5)

if __name__ == '__main__':
    driver = webdriver.Firefox()
    print (driver.get_cookies())
    driver.get('https://44dby.com')
    time.sleep(30)
    print (driver.get_cookies())
    driver.quit()
